/*
 * $Id: CheapestWayToGetItem.java 30 2013-05-25 06:10:03Z antonyhands@gmail.com $
 */
package ru.olympus.antonyhands.ao.ui.analysys;

import java.util.Collections;
import java.util.List;

import ru.olympus.antonyhands.ao.UIHelper;
import ru.olympus.antonyhands.ao.data.AOData;
import ru.olympus.antonyhands.ao.data.entities.AOItem;
import ru.olympus.antonyhands.ao.data.entities.ItemCategory;
import ru.olympus.antonyhands.ao.data.entities.ItemQuantityPair;
import ru.olympus.antonyhands.ao.data.util.ByTitleComparator;
import ru.olympus.antonyhands.ao.data.util.EItemParentType;
import ru.olympus.antonyhands.ao.data.util.ItemByUniversalParentFilter;
import ru.olympus.antonyhands.ao.ui.UpdateMarketPrices;
import ru.olympus.antonyhands.ao.ui.listener.CancelButtonClickListener;
import ru.olympus.antonyhands.ao.util.GoogleIterable;
import ru.olympus.antonyhands.ao.util.LongUtilities;
import ru.olympus.antonyhands.ao.util.StringUtilities;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TreeTable;
import com.vaadin.ui.VerticalLayout;

/**
 * Компонент для определения самого дешёвого способа получить предмет
 * 
 * @author AntonyHands
 * @since 17.05.2013
 */
public class CheapestWayToGetItem extends CustomComponent
{
	private static final long serialVersionUID = -6936281193844572469L;

	private VerticalLayout mainComponent;
	private AOItem _item;

	private Integer _tblId = new Integer(0);

	/**
	 * Компонент для определения самого дешёвого способа получить предмет
	 */
	public CheapestWayToGetItem()
	{
		buildSelectItemComponent();
		setCompositionRoot(mainComponent);
	}

	private CheapestWayToGetItem(AOItem item)
	{
		_item = item;
		buildCraftPricesComponent();
		setCompositionRoot(mainComponent);
	}

	private Component buildSelectItemComponent()
	{
		mainComponent = new VerticalLayout();

		ComboBox categorySelect = new ComboBox("Категория");
		final ComboBox itemSelect = new ComboBox("Предмет");

		categorySelect.setNullSelectionAllowed(false);
		categorySelect.setTextInputAllowed(false);
		categorySelect.setImmediate(true);
		List<ItemCategory> categories = AOData.getInstance()
				.listItemCategories();
		Collections.sort(categories, new ByTitleComparator());
		UIHelper.refillSelect(categorySelect, categories);
		if (categories.size() > 0)
			categorySelect.setValue(categories.get(0).getCode());
		categorySelect.addListener(new ValueChangeListener()
		{
			private static final long serialVersionUID = -2509246364436347100L;

			@Override
			public void valueChange(ValueChangeEvent event)
			{
				Property prop = event.getProperty();
				Predicate<AOItem> predicate = Predicates.alwaysTrue();
				String categoryCode = (String) prop.getValue();
				if (!StringUtilities.isEmpty(categoryCode))
				{
					predicate = new ItemByUniversalParentFilter(
							EItemParentType.ITEM_CATEGORY, categoryCode);
				}
				List<AOItem> list = GoogleIterable
						.with(AOData.getInstance().listItems())
						.filter(predicate).sort(new ByTitleComparator())
						.toArrayList();
				itemSelect.removeAllItems();
				for (AOItem item : list)
				{
					itemSelect.addItem(item.getCode());
					itemSelect.setItemCaption(item.getCode(), item.getTitle());
				}
			}
		});
		mainComponent.addComponent(categorySelect);

		itemSelect.setNullSelectionAllowed(false);
		itemSelect.setTextInputAllowed(false);
		itemSelect.setImmediate(true);
		mainComponent.addComponent(itemSelect);

		HorizontalLayout buttonsLayout = new HorizontalLayout();
		mainComponent.addComponent(buttonsLayout);

		Button okButton = new Button("Далее");
		okButton.addListener(new ClickListener()
		{
			private static final long serialVersionUID = -1669819872382792148L;

			@Override
			public void buttonClick(ClickEvent event)
			{
				AOItem item = AOData.getInstance().getItemByCode(
						(String) itemSelect.getValue());
				if (item == null)
					return;
				List<AOItem> items = item.listItemsInCraftHierarchy();
				Collections.sort(items, new ByTitleComparator());
				UIHelper.changeCurrentComponent(new UpdateMarketPrices(
						new CheapestWayToGetItem(item), items));
			}
		});
		buttonsLayout.addComponent(okButton);

		Button cancelButton = new Button("Отмена");
		cancelButton.addListener(new CancelButtonClickListener());
		buttonsLayout.addComponent(cancelButton);

		return mainComponent;
	}

	private Component buildCraftPricesComponent()
	{
		mainComponent = new VerticalLayout();

		TreeTable table = new TreeTable();
		table.setPageLength(0);
		table.addContainerProperty("title", String.class, null);
		table.addContainerProperty("fixedPrice", String.class, null);
		table.addContainerProperty("craftPrice", String.class, null);
		table.addContainerProperty("marketPrice", String.class, null);
		table.addContainerProperty("quantity", String.class, null);

		table.setColumnHeader("title", "Наименование");
		table.setColumnHeader("fixedPrice", "Фикс цена");
		table.setColumnHeader("craftPrice", "Крафт цена");
		table.setColumnHeader("marketPrice", "Рынок цена");
		table.setColumnHeader("quantity", "Количество");

		fillTable(table, _item, new Long(1));

		mainComponent.addComponent(table);
		return mainComponent;
	}

	private Integer fillTable(TreeTable table, AOItem item, Long quantity)
	{
		Integer id = _tblId++;
		Long craftPrice = item.getCraftPrice();
		Long bestPrice = item.getBestPrice();
		table.addItem(new Object[] { item.getTitle(), item.getFixedPrice(),
				craftPrice, item.getMarketPrice(), quantity }, id);
		table.setCollapsed(id, LongUtilities.equals(craftPrice, bestPrice));
		if (item.getCraftInfo() != null)
		{
			for (ItemQuantityPair pair : item.getCraftInfo()
					.listInputItemsData())
			{
				Integer childId = fillTable(table, pair.getKey(),
						pair.getValue());
				table.setParent(childId, id);
			}
		}
		return id;
	}
}
